package cn.exempale.mscapplication.model.net.callback;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import cn.exempale.mscapplication.emnus.ResultType;
import cn.exempale.mscapplication.vo.BasicResultVO;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 网络访问回调
 *
 * @param <T>
 */
public class BaseCallBack<T> implements Callback<T> {

    private MutableLiveData<Resource<Object>> data = new MutableLiveData<>();
    private MCallBack mCallBack;

    private static final String TAG = "BaseCallBack";


    public BaseCallBack(MCallBack mCallBack) {
        this.mCallBack = mCallBack;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            // 请求成功
            BasicResultVO vo = (BasicResultVO) response.body();
            if (vo != null) {
                if (ResultType.match(vo.getOk()) == ResultType.SUCCESS) {
                    // 成功 返回成功信息
                    data.setValue(Resource.success(vo.getData()));
                    mCallBack.success(data);
                } else {
                    // 失败 返回失败信息
                    data.setValue(Resource.error(vo.getFailed()));
                    mCallBack.error(data);
                }
            }
        } else {
            // 请求失败
            Log.e(TAG, "onResponse:" + "请求失败");
            data.setValue(Resource.error("请求失败"));
            // 失败回调
            mCallBack.error(data);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        // 网络异常
        Log.e(TAG, "+++++++++++++++++++++++++++++++++++++");
        Log.e(TAG, "onFailure: " + "网络异常");
        Log.e(TAG, "onFailure: ", t);
        Log.e(TAG, "+++++++++++++++++++++++++++++++++++++");
        // 失败回调
        data.setValue(Resource.error("网络异常"));
        mCallBack.error(data);
    }
}
